
package com.kanjian.music.activity;

import java.util.ArrayList;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.toolbox.ImageRequest;
import com.kanjian.music.R;
import com.kanjian.music.adapter.MusicControlerPagerAdapter;
import com.kanjian.music.entity.Music;
import com.kanjian.music.fragment.MusicPlayerMusicInfoFragment;
import com.kanjian.music.fragment.MusicPlayerMusicListFragment;
import com.kanjian.music.fragment.MusicPlayerRadioListFragemnt;
import com.kanjian.music.fragment.MusicPlayerRadioMusicInfoFragment;
import com.kanjian.music.listener.PlayerListener;
import com.kanjian.music.service.PlayerService;
import com.kanjian.music.util.FastBlur;
import com.kanjian.music.util.PlayerUtil;
import com.kanjian.music.view.RecyclingImageView;
import com.kanjian.music.volley.VolleyQueue;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelSlideListener;

/**
 * Activity基础类 提供通用方法 如: bindService、 Activity之间的动画切换、向上划出的播放器界面、左上角返回按钮
 * 
 * @author xuyanjun@kanjian.com
 */
public class BaseActivity extends SwipeBackActivity implements PlayerListener {

    protected Button mBtn_back;

    private SlidingUpPanelLayout mMusicPlayerLayout;

    public PlayerService mPlayService;

    protected ProgressBar mPb_playProgress;

    protected TextView mTv_musicName;

    protected TextView mTv_musicianName;

    protected Button mBtn_play;

    protected Button mBtn_next;

    protected RecyclingImageView mIv_musicPic;

    protected TextView mTv_title;

    protected boolean mIsContentViewSeted = true;

    protected ViewPager mMusicControlerViewPager;

    protected ViewPager mRadioControlerViewPager;

    protected MusicControlerPagerAdapter mMusicControlerPagerAdapter;

    protected MusicControlerPagerAdapter mRadioControlerPagerAdapter;

    protected MusicPlayerMusicInfoFragment mPlayerMusicInfoFragment;

    protected MusicPlayerMusicListFragment mPlayerMusicListFragment;

    protected MusicPlayerRadioMusicInfoFragment mPlayerRadioMusicInfoFragment;

    protected MusicPlayerRadioListFragemnt mPlayerRadioListFragemnt;

    ArrayList<Fragment> mMusicPlayerFragmentList = new ArrayList<Fragment>(2);

    ArrayList<Fragment> mRadioPlayerFragmentList = new ArrayList<Fragment>(2);

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        if (mIsContentViewSeted) {
            initBaseView();
        }
    }

    protected void initBaseView() {
        setBackButton();
        mTv_title = (TextView) findViewById(R.id.titlebar_title);
        mTv_musicName = (TextView) findViewById(R.id.music_controler_music_name);
        mTv_musicianName = (TextView) findViewById(R.id.music_controler_musician_name);
        mBtn_play = (Button) findViewById(R.id.music_controler_button_play);
        mBtn_next = (Button) findViewById(R.id.music_controler_button_next);
        mIv_musicPic = (RecyclingImageView) findViewById(R.id.music_controler_pic);
        mMusicControlerViewPager = (ViewPager) findViewById(R.id.music_controler_music_viewpager);
        mRadioControlerViewPager = (ViewPager) findViewById(R.id.music_controler_radio_viewpager);
        mPlayerMusicInfoFragment = MusicPlayerMusicInfoFragment.newInstance();
        mPlayerMusicListFragment = MusicPlayerMusicListFragment.newInstance();
        mPlayerRadioMusicInfoFragment = MusicPlayerRadioMusicInfoFragment.newInstance();
        mPlayerRadioListFragemnt = MusicPlayerRadioListFragemnt.newInstance();
        mMusicControlerPagerAdapter = new MusicControlerPagerAdapter(getSupportFragmentManager());
        mRadioControlerPagerAdapter = new MusicControlerPagerAdapter(getSupportFragmentManager());
        mMusicControlerViewPager.setAdapter(mMusicControlerPagerAdapter);
        mRadioControlerViewPager.setAdapter(mRadioControlerPagerAdapter);

        mMusicPlayerFragmentList.add(mPlayerMusicInfoFragment);
        mMusicPlayerFragmentList.add(mPlayerMusicListFragment);
        mMusicControlerPagerAdapter.setFragmentList(mMusicPlayerFragmentList);
        mRadioPlayerFragmentList.add(mPlayerRadioMusicInfoFragment);
        mRadioPlayerFragmentList.add(mPlayerRadioListFragemnt);
        mRadioControlerPagerAdapter.setFragmentList(mRadioPlayerFragmentList);

        togglePlayerMode();
        renderMusicBackground(PlayerUtil.getCurrentPlayingMusic());
        mBtn_play.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayService != null) {
                    mPlayService.togglePlay();
                }
            }
        });
        mBtn_next.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayService != null) {
                    mPlayService.next(true);
                }
            }
        });
        setMusicPlayerView();
        Intent intent = new Intent(this, PlayerService.class);
        startService(intent);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayService != null) {
            mPlayService.unregisterPlayerListener(this);
        }
        unbindService(conn);
        stopService(new Intent(this, PlayerService.class));
    }

    public void setBackButton() {
        mBtn_back = (Button) findViewById(R.id.titlebar_back);
        if (mBtn_back != null) {
            mBtn_back.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    private void setMusicPlayerView() {
        mMusicPlayerLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
        mPb_playProgress = (ProgressBar) mMusicPlayerLayout
                .findViewById(R.id.music_controler_play_progress);
        if (mMusicPlayerLayout != null) {
            mMusicPlayerLayout.setPanelSlideListener(new PanelSlideListener() {
                @Override
                public void onPanelSlide(View panel, float slideOffset) {
                }

                @Override
                public void onPanelExpanded(View panel) {
                    mPlayerMusicListFragment.refershMusicList();
                }

                @Override
                public void onPanelCollapsed(View panel) {
                    System.out.println("onPanelCollapsed");
                }

                @Override
                public void onPanelAnchored(View panel) {
                    System.out.println("onPanelAnchored");
                }
            });
        }
    }

    protected void setTitle(String title) {
        if (mTv_title != null) {
            mTv_title.setText(title);
        }
    }

    public void startActivityWithAnimation(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.anim_activity_left_slide, R.anim.anim_activity_sink);// R.anim.anim_activity_right_slide);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_activity_float, R.anim.anim_activity_right_slide);
    }

    public void finishWithoutAnimation() {
        super.finish();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (mMusicPlayerLayout != null && mMusicPlayerLayout.isExpanded()) {
                    mMusicPlayerLayout.collapsePane();
                    return true;
                }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mPlayService = ((PlayerService.PlayerServiceBinder) service).getService();
            mPlayService.registerPlayerListener(BaseActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private void renderMusicBackground(Music music) {
        if (music != null) {
            VolleyQueue.getImageRequestQueue().add(
                    new ImageRequest(music.getUserPic(), new Response.Listener<Bitmap>() {
                        @Override
                        public void onResponse(Bitmap bmp) {
                            mIv_musicPic.setImageBitmap(FastBlur.doBlur(bmp, 50, false));
                        }
                    }, 0, 0, Config.ARGB_8888, null));
        }
    }

    // 切换播放器界面 普通和电台
    private void togglePlayerMode() {
        if (PlayerUtil.mPlayerType == PlayerUtil.PLAYERTYPE_MUSICLIST) {
            mMusicControlerViewPager.setVisibility(View.VISIBLE);
            mRadioControlerViewPager.setVisibility(View.GONE);
        } else if (PlayerUtil.mPlayerType == PlayerUtil.PLAYERTYPE_RADIO) {
            mRadioControlerViewPager.setVisibility(View.VISIBLE);
            mMusicControlerViewPager.setVisibility(View.GONE);
        }
    }

    @Override
    public void onProgress(float percent, int playTime) {
        int progress = (int) (percent * 100);
        mPb_playProgress.setProgress(progress);
        mPlayerMusicInfoFragment.onProgress(progress, playTime);
    }

    @Override
    public void onBuffing(int percent) {
        mPb_playProgress.setSecondaryProgress(percent);
    }

    @Override
    public void onPlay(Music music) {
        togglePlayerMode();
        mTv_musicName.setText(music.getMusicName());
        mBtn_play.setText("暂停");
        mTv_musicianName.setText(music.getUserName());
        renderMusicBackground(music);
        mPlayerMusicInfoFragment.refreshMusic();
        mPlayerRadioMusicInfoFragment.refreshMusicPic();
    }

    @Override
    public void onMusicPause() {
        mBtn_play.setText("播放");
    }

    @Override
    public void onContinuePlay() {
        mBtn_play.setText("暂停");
    }

}
